<?php

//微信接口

class WeixinApiAction extends Action{

    public function _initialize(){
        $configs = M('wx_config')->select();
        foreach ($configs as $key => $value) {
            $config[$value['_key']] = $value['_value'];
        }
        C($config);
    }


    public function index(){
        $status = M('wx_config')->where(" _key = 'WX_STATUS'")->getField('_value');
        $status?$this->valid():$this->responseMsg();
    }

	public function valid(){
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    private function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];    
        // 获取Token
        // $token = D('WeixinConfig')->getToken();
        $token = M('wx_config')->where(" _key = 'WX_TOKEN'")->getField('_value');;

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

/**
 * 接受微信信息
 * @return [type] [description]
 */
    public function responseMsg(){				//接受微信消息
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		if(!isset($postStr)){
			echo 'No Access';
			exit;
		}
      	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);

        

        $RX_TYPE = trim($postObj->MsgType);
        //记录之前失误导致没有存入数据库的用户
        // $this->saveUser($postObj);             
        //记录用户发送消息        
        // $this->save_record_info($postObj); 
        // returnText($postObj,$RX_TYPE);
        $this->handle($RX_TYPE,$postObj);
    }

    public function handle($RX_TYPE,$postObj){	//处理事件 
    	// $object = 'Handle'.ucfirst($RX_TYPE).'Controller';
    	// $obj = new $object($postObj);				//调用处理事件的对象
        switch ($RX_TYPE) {
            case 'event':
                $obj = new HandleEventAction($postObj);
                break;
            case 'text':

                $obj = new HandleTextAction($postObj);
                break;
            default:
                $obj = new HandleTextAction($postObj);
                break;
        }

    }

    /**
     * 记录用户操作信息
     * @param  [type] $postObj [description]
     * @return [type]          [description]
     */
    public function save_record_info($postObj){

        $openid             = $postObj->FromUserName.'';
        $data['openid']     = $openid;
        $data['type']       = trim($postObj->MsgType);
        $data['content']    = $postObj->Content.','.$postObj->Event.','.$postObj->EventKey;
        $data['create_time']    = time();
        $res                = M('weixin_record_info')->add($data);

    }


/**
 * 记录失误导致没有记录的用户
 * @return [type] [description]
 */
    public function saveUser($postObj){

        $openid     = $postObj->FromUserName.'';

        $user_id    = M('weixin_user')->where("openid='$openid'")->getField('id');

        if($user_id){                   
            //已经存在该用户
            //更新操作时间
            $access_token   = get_access_token();
            $user_info      = get_user_info($openid,$access_token);
            // returnText($postObj,serialize($user_info));
            $user_info['isSub']      =   1;
            $user_info['updatetime'] =   time();
            $res  =   M('weixin_user')->where('id='.$user_id)->save($user_info);  

        }else{                          
            //不存在
            $access_token   = get_access_token();
            // returnText($postObj,' .'.$access_token );

            $user_info      = get_user_info($openid,$access_token,$postObj);

            if(empty($user_info)){
                $user_info['openid'] = $openid.'';
                $user_info['subscribe_time'] = time();
                $user_info['updatetime'] = time();
            }
            // returnText($postObj,' .'.join(' '.$user_info['nickname']) );
            $res            = M('weixin_user')->add($user_info);
            // returnText($postObj,' .'.$res );
            //returnText($postObj,'不存在');
        }
    }

}//----------END WxController